﻿using Spire.Doc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace Mozhi.Abp.Core.Offices.Words
{
    public class SpireWordHandler : IWordHandler
    {
        public Stream GetPrintFileStream(Stream templateStream, List<PrintData> datas, PrintOption option)
        {
            var documents = new List<Document>();

            if (datas == null || datas.Count == 0)
                throw new ArgumentNullException("datas");

            foreach(var data in datas)
            {
                Document document = new Document();
                document.LoadFromStream(templateStream, FileFormat.Docx);

                var fieldNames = data.MergeFieldDict.Keys.ToArray();

                var fieldValues = data.MergeFieldDict.Values.ToArray();

                document.MailMerge.Execute(fieldNames, fieldValues);

                var table = data.MergeFieldDataSet != null && data.MergeFieldDataSet.Tables.Count > 0 ? data.MergeFieldDataSet.Tables[0] : null;

                if (table != null)
                    document.MailMerge.ExecuteWidthRegion(table);

                documents.Add(document);
            }

            var targetDocument = documents.First();

            var sourceDocuemnts = documents.Where(x => x != targetDocument).ToList();

            foreach (var sourceDocument in sourceDocuemnts)
            {
                //重起一页
                Section firstSection = sourceDocument.Sections[0];

                targetDocument.Sections.Add(firstSection);
            }

            var result = new MemoryStream();

            targetDocument.SaveToStream(result, option.FileType == FileType.PDF ? FileFormat.PDF : FileFormat.Docx);

            return result;
        }

        #region
        
        #endregion
    }
}
